<?php
namespace app\admin\model\finance;
use think\Model;

/**
 *   提现申请表
 * Class AgentCashout
 * @package app\admin\model\finance
 */
class AgentCashout extends Model
{
    protected $name='agent_cashout';

    public function agent(){
        return $this->belongsTo("app\admin\model\agent\Agent",'agent_id','agent_id');
    }
    /**
     * 获取订单列表
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($query = [])
    {
        // 设置查询条件
        !empty($query) && $this->setQueryWhere($query);

            // 获取列表数据
            return $this->with(['agent'])
                ->alias('cash')
                ->join('agent', 'agent.agent_id=cash.agent_id')
                ->order(['cash.create_time' => 'desc'])
                ->paginate(15, false, [
                    'query' => request()->request()
                ]);


    }

    /**
     * 设置查询条件
     * @param $query
     */
    private function setQueryWhere($query)
    {
        // 设置默认的检索数据
        $params = $this->setQueryDefaultValue($query, [
            'sh_status' => '-1',
            'kp' => '-1',
        ]);

        if (isset($query['search']) && !empty($query['search'])) {
            $this->where('agent.company_name|agent.real_name', 'like', '%' . trim($query['search']) . '%');
        }
        //是否开票
        !empty($params['kp']) > -1 && $this->where('cash.isKaipiao', '=', (int)$params['kp']);
        // 审核状态
       // $params['sh_status'] > -1 && $this->where('cash.sh_status', '=', (int)$params['sh_status']);
        // 起始时间
        !empty($params['start_time']) && $this->where('cash.create_time', '>=', strtotime($params['start_time']));
        // 截止时间
        !empty($params['end_time']) && $this->where('cash.create_time', '<', strtotime($params['end_time']) + 86400);
    }

    /**
     * 设置默认的检索数据
     * @param $query
     * @param array $default
     * @return array
     */
    protected function setQueryDefaultValue(&$query, $default = [])
    {
        $data = array_merge($default, $query);
        foreach ($query as $key => $val) {
            if (empty($val) && isset($default[$key])) {
                $data[$key] = $default[$key];
            }
        }
        return $data;
    }


    /**
     * 打印订单列表
     * @param $dataType
     * @param array $query
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getExportList($query = [],$start, $limit,$count = false)
    {
        // 检索查询条件
        !empty($query) && $this->setQueryWhere($query);
        if($count==true){
            // 获取数据列表
            return $this->with(['agent'])
                ->alias('cash')
                ->join('agent', 'agent.agent_id=cash.agent_id')
                ->order(['cash.create_time' => 'desc'])
                ->count();
        }

        // 获取数据列表
        $list =  $this->with(['agent'])
            ->alias('cash')
            ->join('agent', 'agent.agent_id=cash.agent_id')
            ->order(['cash.create_time' => 'desc'])
            ->limit($start,$limit)
            ->select();

        // 表格内容
        $dataArray = [];
        foreach ($list as $order) {
            $dataArray[] = [
                '申请主体' => $this->filterNameValue($order),
                '服务商类型' => $this->filterTypeValue($order['type']),
                '提现金额' => $this->filterValue($order['money']),
                '是否开票' => $this->filterKPValue($order['isKaipiao']),
                '实际到账金额' => $this->filterValue($order['rel_money']),
                '申请状态' => $this->filterStatusValue($order['sh_status']),
                '申请时间' => $this->filterValue($order['create_time'])
                ];

        }

        return  $dataArray;

    }

    /**
     * 订单导出
     * @param $dataType
     * @param $query
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function exportList( $query)
    {

        header("Content-type:text/html;charset=utf-8");
        $mpName = '提现明细';
        $limit = 500;//每次只从数据库取50000条以防变量缓存太大
        // buffer计数器
        $cnt = 0;
        set_time_limit(0);

        //计算总的数据
        $sqlCount = $this->getExportList($query,0, $limit,true);

        $xlsTitle = [
            '申请主体', '服务商类型', '提现金额', '是否开票', '实际到账金额', '申请状态', '申请时间'
        ];

        $fileName = $mpName . date('Y-m-d');// 文件名称可根据自己情况设定

        // 输出Excel文件头，可把user.csv换成你要的文件名
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');

        $fileNameArr = array();

        // 逐行取出数据，不浪费内存
        for ($i = 0; $i < ceil($sqlCount / $limit); $i++) {

            $fp = fopen($fileName . '_' . $i . '.csv', 'w'); //生成临时文件
            fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
            // chmod('attack_ip_info_' . $i . '.csv',777);//修改可执行权限
            $fileNameArr[] = $fileName . '_' . $i . '.csv'; // 将数据通过fputcsv写到文件句柄
            fputcsv($fp, $xlsTitle);
            $start = $i * $limit;
            $dataArr = $this->getExportList($query, $start, $limit,false);

            foreach ($dataArr as $a) {
                $cnt++;
                if ($limit == $cnt) {
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    ob_flush();
                    flush();
                    $cnt = 0;
                }
                fputcsv($fp, $a);
            }
            fclose($fp);  //每生成一个文件关闭
        }

        //进行多个文件压缩
        $zip = new \ZipArchive();
        $filename = $fileName . ".zip";
        $zip->open($filename, $zip::CREATE);   //打开压缩包
        foreach ($fileNameArr as $file) {
            $zip->addFile($file, basename($file));   //向压缩包中添加文件
        }
        $zip->close();  //关闭压缩包
        foreach ($fileNameArr as $file) {
            unlink($file); //删除csv临时文件
        }

        //输出压缩文件提供下载
        header("Cache-Control: max-age=0");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . basename($filename)); // 文件名
        header("Content-Type: application/zip"); // zip格式的
        header("Content-Transfer-Encoding: binary"); //
        header('Content-Length: ' . filesize($filename)); //
        @readfile($filename);//输出文件;
        unlink($filename); //删除压缩包临时文件
    }

    /**
     * 表格值过滤
     * @param $value
     * @return string
     */
    private function filterValue($value)
    {
        return "\t" . $value . "\t";
    }

    /**
     * 日期值过滤
     * @param $value
     * @return string
     */
    private function filterTime($value)
    {

        if (!$value) return '';
        return $this->filterValue(date('Y-m-d H:i:s', $value));
    }


    private function filterTypeValue($value){
        return  $value==0 ? '品牌商' : ( $value==1 ? '运营商' :'合伙人' );

    }

    private function filterNameValue($data){

        if ($data['type'] ==0){
            return $data['company_name'];
        }elseif ($data['type']==1  ){
            return !empty($data['company_name']) ? $data['company_name'] : $data['real_name'];
        }elseif ($data['type']==2){
            return !empty($data['company_name']) ? $data['company_name'] : $data['real_name'];
        }
    }


    private function filterKPValue($value){
        return  $value==0 ? '不开票' :'开票';
    }

    private function filterStatusValue($value){
        return  $value==0 ? '待审核' : ( $value==1 ? '已通过' :'已拒绝' );
    }

}